import webbrowser
import sinaweibopy3
import json
import pandas as pd

try:
    # step 1 : sign a app in weibo and then define const app key,app srcret,redirect_url
    APP_KEY = '3348254988'
    APP_SECRET = 'd15c60dc13f4a1a5b3b5c644e8a3bf3c'
    REDIRECT_URL = 'http://api.weibo.com/oauth2/default.html'
    # step 2 : get authorize url and code
    client = sinaweibopy3.APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL)
    url = client.get_authorize_url()
    # print(url)
    webbrowser.open_new(url)
    # step 3 : get Access Token
    # Copy the above address to the browser to run, 
    #enter the account and password to authorize, the new URL contains code
    result = client.request_access_token(
        input("please input code : "))  # Enter the CODE obtained in the authorized address
    print(result)
    # At this point, the access_token and expires_in should be saved,
    # because there is a validity period.A
    # If you need to send the microblog multiple times in a short time,
    # you can use it repeatedly without having to acquire it every time.
    client.set_access_token(result.access_token, result.expires_in)

    # step 4 : using api by access_token
    # 获取关注人列表
    result = client.fs_friends('lightzhen')
    print(json.dumps(result,indent=2,ensure_ascii=False))
    fds = []
    for u in result['users']:
        print("\n",u['screen_name'])
        print(u['location'])
        if('status' not in u):
            print('not found\n')
            continue
        print(u['status']['text'])
        fds.append([u['screen_name'], u['location'], u['status']['text']])

    # 创建关注人的DataFrame
    df_fd = pd.DataFrame(fds, columns=['name', 'location', 'status'])
    # 统计关注人地理位置分布
    print(df_fd['location'].value_counts())
except ValueError:
    print('pyOauth2Error')